package com.yanggu.mapreduce.reducejoin;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

/**
 * @version V1.0
 * @author: YangGu
 * @date: 2020/2/7 21:23
 * @description:
 */
public class TableBeanReducer extends Reducer<Text, TableBean, TableBean, NullWritable> {

    private List<TableBean> orderBeanList = new ArrayList<>();

    @Override
    protected void reduce(Text key, Iterable<TableBean> values, Context context) throws IOException, InterruptedException {
        //这里是清空原有List中的order数据
        orderBeanList.clear();

        //如果想要实现left join的效果。可以将这里的pname设置为默认值null的字符串。
        //如果对应的pid没有pname。那么使用默认的null字符串代替
        String pname = "null";

        // 1. 通过flag区分出是来自order还是product
        for (TableBean value : values) {
            if ("order".equals(value.getFlag())) {
                TableBean tempBean = new TableBean();
                try {
                    //这里使用全新的对象
                    BeanUtils.copyProperties(tempBean, value);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                orderBeanList.add(tempBean);
            } else if ("product".equals(value.getFlag())){
                pname = value.getPName();
            }
        }

        //2. 将produce中的pid用pname替代。并且写出
        for (TableBean order : orderBeanList) {
            order.setPName(pname);
            context.write(order, NullWritable.get());
        }
    }
}
